 package sys.controller;

 import com.alibaba.fastjson.JSON;
 import com.init.ConfigInitial;
 import com.init.SingletonCache;
 import com.init.cachelist.CacheList;
 import com.model.Login;

 import com.service.LoginService;

 import com.util.LogUtil;
 import com.util.PagedRequest;
 import com.util.PagedResult;

 import com.util.PathUtil;
 import net.sf.json.JSONException;
 import net.sf.json.JSONObject;
 import org.apache.commons.io.FileUtils;
 import org.springframework.beans.factory.annotation.Autowired;

 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.multipart.MultipartFile;
 import sys.model.Backups;
 import sys.model.User;
 import sys.service.TreeService;
 import sys.service.UserService;
 import sys.util.UserUtil;

 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import java.io.File;
 import java.io.IOException;
 import java.net.URLDecoder;
 import java.text.SimpleDateFormat;
 import java.util.*;


 @Controller
 @RequestMapping("")
 public class UserController {

     @Autowired
     UserService userService;
     @Autowired
     TreeService treeService;

     /*
     * 获取用户列表
     * */
     @RequestMapping(value = "/getAllUser", method = { RequestMethod.POST,
             RequestMethod.GET },produces = "text/plain;charset=UTF-8")
         @ResponseBody
         public String getAllUser(HttpServletRequest request,PagedRequest pagedRequest,String name,String start,String end,String flag){
             LogUtil.info("获取用户列表=====>");
             LogUtil.info("分页参数:"+	pagedRequest.getPage());
             LogUtil.info("分页页数:"+	pagedRequest.getRows());
             LogUtil.info("排序序名:"+	pagedRequest.getSidx());
             LogUtil.info("排序方式:"+	pagedRequest.getSord());
             LogUtil.info("查找名称:"+	name);
             LogUtil.info("入学时间:"+	start+" ~ "+end);
             Map map=new HashMap();
            map.put("name",name);
            map.put("start",start);
            map.put("end",end);
            map.put("page",pagedRequest.getPage());
            map.put("rows",pagedRequest.getRows());
            map.put("sidx",pagedRequest.getSidx());
            map.put("sord",pagedRequest.getSord());
         User user=UserUtil.getUser(request);
         if(flag.equals("role")&&user!=null&& user.getUsertype()>0){
             map.put("usertype",user.getUsertype());
             if(user.getUsertype()==1){
                 map.put("usertype",0);
             }
         }
             PagedResult<User> userList=userService.getAllUser(map);
             return   JSON.toJSONString(userList);


         }

     /*
 * 获取用户树
 * */
     @RequestMapping(value = "/getAllUserTree", method = { RequestMethod.POST,
             RequestMethod.GET },produces = "text/plain;charset=UTF-8")
     @ResponseBody
     public String getAllUserTree(){
         LogUtil.info("获取用户树===>");
         Map map=new HashMap();
         map.put("sidx","usertype");
         map.put("sord","asc");
         List<User> userList=userService.getAllUserTree(map);

         return   JSON.toJSONString(userList);


     }
     /*
     * 个人修改
     * */

         @RequestMapping(value = "/UserUpdate", method = { RequestMethod.POST,
                 RequestMethod.GET },produces = "text/plain;charset=UTF-8")
         @ResponseBody
         public String UserUpdate(HttpServletRequest request,HttpServletResponse response,User user,@RequestParam(value = "file", required = false)MultipartFile file) throws Exception {
             LogUtil.info("个人信息修改====>");
             JSONObject json = new JSONObject();
             if(user!=null&&user.getId()!=null&&file!=null&&!file.isEmpty()){
                 LogUtil.info("图片上传====>");
                 String path="image/upload/";
                 String urlpath = PathUtil.getWebRootPath()+path;
                 File targetFile = new File(urlpath,"user-"+user.getId()+"-"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".jpg");
                 user.setUrl(path+targetFile.getName());
                 if(!targetFile.exists()){
                     targetFile.mkdirs();
                 }
                 //保存
                 try {
                     file.transferTo(targetFile);
                 } catch (Exception e) {
                     LogUtil.info("图片上传失败====>");
                 }
             }
             if(user!=null&&user.getId()!=null){
                 user.setRealname(URLDecoder.decode(user.getRealname(), "utf-8"));

                 System.out.println(JSON.toJSON(user));
                  int i=userService.update(user);
                 if(i>0){
                     UserUtil.updateUser(request,user);
                     json.put("status", "success");
                     json.put("msg", "修改成功");
                     return json.toString();
                 }
             }

                 json.put("status", "error");
                 json.put("msg", "修改错误");
                 return json.toString();

         }

     /*
        * 管理员修改
        * */
     @RequestMapping(value = "/UserUpdate2", method = { RequestMethod.POST,
             RequestMethod.GET },produces = "text/plain;charset=UTF-8")
     @ResponseBody
     public String UserUpdate2(HttpServletRequest request,HttpServletResponse response,User user,@RequestParam(value = "file", required = false)MultipartFile file) throws Exception {
         LogUtil.info("用户信息修改====>");
         JSONObject json = new JSONObject();
         if(user!=null&&user.getId()!=null){

          // System.out.println(JSON.toJSON(user));
           //  int i=1;
               int i=userService.update(user);
             if(i>0){
                 json.put("status", "success");
                 json.put("msg", "修改成功");
                 return json.toString();
             }
         }
         json.put("status", "error");
         json.put("msg", "修改错误");
         return json.toString();

     }

     /********************************************************
      * 函数名: editPwd
      * 功能     : 编辑用户密码
      * 作者      ：lhong 2016-9-30
      * 参数表: @param response
      * 参数表: @return
      * 返回值: String
      * 修改记录：
      *          日期                 修改人                 修改说明
      * @throws JSONException
      * @throws IOException
      *******************************************************/
     @RequestMapping(value="/editPwd",method={RequestMethod.POST,RequestMethod.GET},produces = "text/plain;charset=UTF-8")
     @ResponseBody     //返回Json
     public String editPwd(@RequestParam("editOldPwd")String editOldPwd,@RequestParam("editNewPwd")String editNewPwd,@RequestParam("reqtime")String reqtime,
                           HttpServletRequest request,HttpSession session,HttpServletResponse response) throws JSONException, IOException{
         User user = UserUtil.getUser(request);
         JSONObject json = new JSONObject();
         json.put("status", "error");
         json.put("msg", "原密码错误");
         json.put("oprate", "修改失败");
         if(user!=null){
             Map map =new HashMap();
             map.put("userid",user.getId());
             map.put("newpwd",editNewPwd);
             map.put("oldpwd",editOldPwd);
             int i=userService.editPwd(map);
             if(i>0) {
                 session.removeAttribute("user");
                 json.put("status", "success");
                 json.put("oprate", "修改成功");
                 json.put("msg", "10后跳转登入页重新登入!");
             }
             return json.toString();
         }
            return json.toString();



     }

  /*
     * 用户名验证
     * */

         //验证用户名
         @RequestMapping(value = "/vaName", method = { RequestMethod.POST,
                 RequestMethod.GET })
         @ResponseBody
         public String vaName(HttpServletRequest request,HttpServletResponse response) throws Exception {
             String userName=request.getParameter("userName");
             JSONObject json = new JSONObject();
             if(!userName.equals("shugen"))
             json.put("data", "true");
             else json.put("data", "false");
             LogUtil.info("验证结果:"+json.toString());
             return json.toString();
         }
         @RequestMapping(value = "/addUser", method = { RequestMethod.POST,
                 RequestMethod.GET },produces = "text/plain;charset=UTF-8")
         @ResponseBody
         public String addUser(HttpServletRequest request,HttpServletResponse response,User user) throws Exception {
             LogUtil.info("添加用户====>");
             JSONObject json = new JSONObject();
             Random random = new Random();
             int t=random.nextInt(10);
             String url="image/default_t/t"+t+".jpg";
             user.setUrl(url);
             System.out.println(JSON.toJSON(user));
             int i=userService.insert(user);
             if(i>0){
                 json.put("status", "true");
                 json.put("msg", "添加成功");
             }
             else{
                 json.put("status", "false");
                 json.put("msg", "添加错误,账号已存在");
             }

             return json.toString();
         }
         @RequestMapping(value = "/deleteUser", method = { RequestMethod.POST,
                 RequestMethod.GET },produces = "text/plain;charset=UTF-8")
         @ResponseBody
         public String deleteUser(HttpServletRequest request,HttpServletResponse response,String id) throws Exception {
             LogUtil.info("删除用户====>");
             JSONObject json = new JSONObject();
             try {
                 int ID = Integer.valueOf(id);
                    User user=UserUtil.getUser(request);
                 if(user.getId()==ID){
                     json.put("status", "false");
                     json.put("msg", "不能删除自己");
                 }
                 else{
                     int i= userService.deleteById(ID);
                     if(i>0){
                         json.put("status", "true");
                         json.put("msg", "删除成功");
                     }
                     else{
                         json.put("status", "false");
                         json.put("msg", "删除错误");
                     }
                 }

                 return json.toString();
             }
             catch (Exception e){
                 json.put("status", "false");
                 json.put("msg", "为登入账号或没有权限!");
             }
             return json.toString();
         }

     /**
      * 跳转登入页
      * @return
      */
     @RequestMapping("/loginPage")
     public String loginPage(){
         return "login";
     }
/*
* 门户页
* */
     @RequestMapping("/default")
     public String SoPage(){
         return "jsp/in/in";
     }



     /**
      *  账号登入--存入 session
      * @param username
      * @param password
      * @return
      */
     @RequestMapping(value = "/getOneUser", method = { RequestMethod.POST,
             RequestMethod.GET },produces = "text/plain;charset=UTF-8")
     @ResponseBody
     public String getOneUser(String id,HttpServletRequest request){
         LogUtil.info("获取个人信息===>");
         Integer ID;
         try {
            ID=Integer.parseInt(id);
         }
         catch (Exception e){
             ID=0;
         }
         if(ID==0){
             HttpSession session = request.getSession();
             Object ss= session.getAttribute("user");
             if(ss!=null&&ss.getClass()==User.class)
                ID= ((User)ss).getId();
         }

         User user=userService.selectById(ID);
         if(user==null){
             return null;
         }
         else {
            return  JSON.toJSONString(user);
         }



     }
     /**
      *  账号登入--存入 session
      * @param username
      * @param password
      * @return
      */
     @RequestMapping("/login")
     @ResponseBody
     public String login(String username,String password,HttpServletRequest request){
         LogUtil.info("账号验证===>"+username);
         JSONObject json = new JSONObject();
         User user=userService.getUser(username,password);
         if(user==null){
             json.put("data", "false");
             LogUtil.info("验证失败===>");
         }
         else {
             json.put("data", "true");
             HttpSession session = request.getSession();
             session.setAttribute("user",user);
         /*    Object ss= session.getAttribute("user");
             if(ss!=null&&ss.getClass()==User.class)
                 System.out.println(((User)ss).getUsername());*/
             LogUtil.info("验证通过===>进入首页");
         }
         return json.toString();


     }

     @RequestMapping("/tree")
     @ResponseBody
     public String tree(HttpServletResponse response,HttpServletRequest request) throws IOException {
         LogUtil.info("用户菜单获取====>");
         response.setCharacterEncoding("UTF-8");
         response.setHeader("Pragma","No-cache");
         response.setHeader("Cache-Control","no-cache");
         response.setDateHeader("Expires", 0);
         User user=UserUtil.getUser(request);
         if(user!=null) {
             String treeStr = (String) SingletonCache.getCacheElement(user.getUsertype(), SingletonCache.getCache(ConfigInitial.Tree));
             if (treeStr == null) {
                 new CacheList().initTree(user.getUsertype());
                 treeStr = (String) SingletonCache.getCacheElement(user.getUsertype(), SingletonCache.getCache(ConfigInitial.Tree));
             }
             // 因为取菜单树只需要UserId,所以将保存的对像强转成基类User就可以了
             HttpSession session = request.getSession();
             // System.out.println(treeStr);
             response.getWriter().print(treeStr);
         }
         return null;


     }
/*系统备份*/

     @RequestMapping(value = "/backups", method = { RequestMethod.POST,
             RequestMethod.GET },produces = "text/plain;charset=UTF-8")
     @ResponseBody
     public String backups(HttpServletRequest request)  {
         LogUtil.info("系统备份");
         JSONObject json= new JSONObject();
         try {
             String filepath = PathUtil.getWebRootPath() + "/system_sql";
             File file = new File(filepath);
             if (!file.exists()) {
                 file.mkdirs();
             }
             //  String backupCmd = "mysqld -u root [-p 123456] database [sj] > sj.sql";
             Process exec = Runtime.getRuntime().exec(ConfigInitial.opt + filepath + "/"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".sql");
             json.put("status", "success");
             json.put("opare", "正在备份数据");
             json.put("msg", "10s后稍后会自动重载页面数据");
         }
         catch (Exception e){
             json.put("status", "false");
             json.put("msg", "请检查系统配置");
             json.put("opare", "备份失败");
         }
         return json.toString();
     }
     /*使用系统备份*/
     @RequestMapping(value = "/usebackups", method = { RequestMethod.POST,
             RequestMethod.GET },produces = "text/plain;charset=UTF-8")
     @ResponseBody
     public String usebackups(HttpServletRequest request,String filepath)  {
         LogUtil.info("使用系统备份");
         JSONObject json= new JSONObject();
         System.out.println(filepath);
         try {
             File file =new File(filepath);
             if(!file.exists()){
                 json.put("status", "warning");
                 json.put("msg", "覆盖失败,文件丢失");
                 return json.toString();
             }
             Process exec = Runtime.getRuntime().exec(ConfigInitial.ipt + filepath);
             json.put("status", "success");
             json.put("msg", "覆盖成功");
         }
         catch (Exception e){
             json.put("status", "warning");
             json.put("msg", "覆盖失败");
         }
         return json.toString();
     }


     /*删除系统备份*/
     @RequestMapping(value = "/delbackups", method = { RequestMethod.POST,
             RequestMethod.GET },produces = "text/plain;charset=UTF-8")
     @ResponseBody
     public String delbackups(HttpServletRequest request,String filepath)  {
         LogUtil.info("删除系统备份");
         JSONObject json= new JSONObject();
         try {
             System.out.println(filepath);
             File file =new File(filepath);
             boolean flag=false;
             if(file.isFile()&&file.exists()){
                 file.delete();
                 flag=true;
             }
             if(flag) {
                 json.put("status", "success");
                 json.put("msg", "删除成功");
             }
             else {
                 json.put("status", "warning");
                 json.put("msg", "删除失败");
             }
         }
         catch (Exception e){
             json.put("status", "warning");
             json.put("msg", "删除出现错误");
             return json.toString();
         }
         return json.toString();
     }

/*获取系统备份*/

     @RequestMapping(value = "/getbackups", method = { RequestMethod.POST,
             RequestMethod.GET },produces = "text/plain;charset=UTF-8")
     @ResponseBody
     public String getbackups(HttpServletRequest request) throws IOException {
         LogUtil.info("获取系统备份");
         String  filepath=PathUtil.getWebRootPath()+"/system_sql";
         File file = new File(filepath);
         List<Backups> list =new ArrayList<>();


         if(!file.exists()){
             file.mkdirs();
         }
         if (file.isDirectory()) {
             String[] filelist = file.list();
             for (int i = 0; i < filelist.length; i++) {
                 File readfile = new File(filepath + "\\" + filelist[i]);
                 if (!readfile.isDirectory()) {
                     list.add(new Backups(readfile.getName(),readfile.getPath()));
                 }
             }

         }
         return JSON.toJSONString(list);
     }

     /*  下载备份*/
     @RequestMapping(value="/loadbackups",method={RequestMethod.POST,RequestMethod.GET})
     public ResponseEntity<byte[]> loadbackups(HttpServletRequest request, String filepath) throws IOException {
         HttpHeaders headers = new HttpHeaders();
         File file=new File(filepath);
         String fileName=file.getName();
         headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "iso-8859-1"));
         return (new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED));

     }

      /*   @RequestMapping("/thread")
         public void  threadTest(){
             Login l=new Login();
             l.setId(1);
             l.setUserName("shugen");
             (new ExportThread(l)).start();
         }*/

 }
